/**
 * Created by wangzilong on 2017/4/11.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ScrollView,
    TouchableOpacity,
    TextInput,
    ListView,
    Modal,
    DatePickerAndroid,
    DatePickerIOS,
    Platform,
    Alert
} from 'react-native';
import ImageWrapper from '../components/ImageWrapper';
import NavigationBar from '../components/NavigationBar';
import GoodsItem from '../components/GoodsItem';
import shopService from '../lib/services/shopService';
import StorageUser from '../lib/plugins/StorageUser';
import ImageCropPicker from 'react-native-image-crop-picker';
var Dimensions = require('Dimensions');
const { width, height } = Dimensions.get('window');

export default class PublicTask extends Component{
    constructor(props) {
        super(props);
        this.token = '';
        this.userId = '';
        this.shopId = '';
        this.state = {
            startTime:'开始时间',
            startTimeStamp:'',
            endTime:'结束时间',
            endTimeStamp:'',
            imgUriList:[],
            imgDataList:[],
            title:'',
            content:'',
            personNum:0,
        };
    }
    componentDidMount() {
        var $this = this;
        StorageUser._getUser()
            .then(data=>{
                if(data.token){
                    $this.token = data.token;
                }
                if(data.userId){
                    $this.userId = data.userId;
                }
                if(data.shopId){
                    $this.shopId = data.shopId;
                }
                // InteractionManager.runAfterInteractions(() => {
                //     
                // });              
            }).catch(err=> {
                console.log(err)
            });
    }
    renderImg(){
        var list = this.state.imgUriList;
        return(
            list.map((item,i)=>{
                return(
                    <View key={i}>
                        <TouchableOpacity style={{paddingTop:10,paddingRight:10}} onPress={()=>this.selectItem(i)}>
                            <ImageWrapper style={{width:20,height:20,position:'absolute',top:0,right:0,zIndex:1000}} icon={'stop'}/>
                            <Image style={{width:60,height:60}} source={{uri:item.path}}/>               
                        </TouchableOpacity>
                        
                    </View>
                )
            })
        )
    }
    render(){
        return (
            <View style={styles.container}>
                <NavigationBar 
                    leftIcon={'left'} 
                    titleText={'发布活动'} 
                    leftPress={()=>this.goBack()}
                    rightText={'发布'}
                    rightTextStyle={{color:'#fff'}}
                    rightTextPress={()=>this.publicActive()}/>
                <ScrollView>
                    <View style={{backgroundColor:'#fff'}}>
                        <TextInput
                            placeholder={'活动标题'}
                            underlineColorAndroid={'transparent'}
                            onChangeText={(text)=>this.getTitle(text)}/>
                    </View>
                    <View style={{backgroundColor:'#fff',marginTop:10}}>
                        <TextInput placeholder={'活动内容'}
                            underlineColorAndroid={'transparent'}
                            textAlignVertical={'top'}
                            multiline={true}
                            numberOfLines={7}
                            onChangeText={(text)=>this.getContent(text)}/>
                        <View style={{flexDirection:'row',flexWrap:'wrap',paddingLeft:10,paddingBottom:10}}>
                            {this.renderImg()}
                            <TouchableOpacity onPress={()=>this.choseImg()} style={{marginBottom:10,width:60,height:60,marginTop:10}}>
                                <ImageWrapper width={60} height={60} icon={'addImg'}/>
                            </TouchableOpacity>
                        </View>
                        
                    </View>
                    <View style={{height:30,justifyContent:'center',paddingLeft:10,marginTop:10,backgroundColor:'#fff'}}>
                        <Text>活动时间</Text>
                    </View>
                    <View style={{flexDirection:'row',backgroundColor:'#fff',height:30}}>
                        <View style={[styles.timeTextBox,{flex:1}]}>
                            <Text onPress={this.showPicker.bind(this, 'preset', 1)}>{this.state.startTime}</Text>
                        </View>
                        <View style={[styles.timeTextBox,{width:40}]}>
                            <Text>~</Text>
                        </View>
                        <View style={[styles.timeTextBox,{flex:1}]}>
                            <Text onPress={this.showPicker.bind(this, 'preset', 2)}>{this.state.endTime}</Text>
                        </View>
                    </View>
                    <View style={{backgroundColor:'#fff',marginTop:10}}>
                        <TextInput
                            placeholder={'参与人数'}
                            underlineColorAndroid={'transparent'}
                            onChangeText={(text)=>this.getPersonNum(text)}/>
                    </View>
                </ScrollView>
            </View>
        )
    }

    goBack(){
        this.props.navigation.state.params.upData();
        this.props.navigation.goBack();
    }

    selectItem(index){
        var imgList = this.state.imgUriList;
        var dataList = this.state.imgDataList;
        imgList.splice(index,1);
        dataList.splice(index,1);
        this.setState({
            imgUriList:imgList,
            imgDataList:dataList,
        })
    }

    getTitle(text){
        this.setState({
            title:text
        })
    }

    getContent(text){
        this.setState({
            content:text
        })
    }

    getPersonNum(text){
        this.setState({
            personNum:text
        })
    }

    async showPicker(stateKey, staturs) {
        try {
            var newState = {};
            const {action, year, month, day} = await DatePickerAndroid.open({
                date: new Date(),
                mode:'spinner'
            });      
            if (action === DatePickerAndroid.dismissedAction) {
                newState[stateKey + 'Text'] = 'dismissed';
            } else {
                var date = new Date(year, month, day);
                newState[stateKey + 'Text'] = date.toLocaleDateString();
                newState[stateKey + 'Date'] = date;
                var newDate = '' + year + '-' + ((month+1)>9?(month+1):'0'+(month+1)) + '-' + (day>9?day:'0'+day);
                if(staturs==1){
                    this.setState({
                        startTime:newDate,
                        startTimeStamp:date.getTime()/1000,
                    })
                }else if(staturs==2){
                    this.setState({
                        endTime:newDate,
                        endTimeStamp:date.getTime()/1000,
                    })
                }
            }

            this.setState(newState);
        } catch ({code, message}) {
            console.warn(`Error in example '${stateKey}': `, message);
        }
    }

    // 选择头像上传
    choseImg(){
        var $this = this;
        if(this.state.imgUriList.length==5){
            return;
        }
        ImageCropPicker.openPicker({
            multiple: true,
            maxFiles: 9,
            mediaType: 'photo'
        }).then(images => {
            var len = images.length;
            var arr = [];
            for(var i=0;i<len;i++){
                var source = {};
                if (Platform.OS === 'android') {
                    source = {path: images[i].path};
                    arr.push(source);
                } else {
                    source = {path: images[i].path.replace('file://', '')};
                    arr.push(source);
                }
            }
            var uriArr = $this.state.imgUriList;
            var dataArr = $this.state.imgDataList;
            uriArr = uriArr.concat(arr);
            dataArr = dataArr.concat(images);
            $this.setState({
                imgUriList:uriArr,
                imgDataList:dataArr,
            });
        }).catch((err)=> {
                console.log(err);
            });
                
    }

    publicActive(){
        var $this = this;
        var imgArr = [];
        var len = this.state.imgDataList.length;
        for(var i=0;i<len;i++){
            var name = 'img'+(i+1);
            imgArr[name] = this.state.imgDataList[i].path;
        }
        shopService.addActivity(function(data){
            alert(JSON.stringify(data))
            if(data.code==10000){
                Alert.alert(
                    '提示信息',
                    '发布成功',
                    [{text: '确定', onPress: () => $this.goBack()}])
            }
        },$this.state.title,$this.state.content,$this.state.startTimeStamp,$this.state.endTimeStamp,$this.state.personNum,$this.userId,imgArr,$this.shopId,$this.token)
    }

}

const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'#EFEFF4',
        ...Platform.select({
            ios: {
                marginTop: 20
            },
            android: {
                marginTop:0
            },

        }),
    }, 
    timeTextBox:{
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:'#fff'
    }

});